<template>
  <view class="container">
    <u-navbar
      :is-fixed="false"
      :border-bottom="false"
      :is-back="false"
      :background="{ background: '#e58b8a' }"
      title="健康记录"
      title-color="#000"
    >
    </u-navbar>
    <u-notice-bar v-if="userInfo.notice" mode="horizontal" :list="[userInfo.notice]"></u-notice-bar>
    <u-toast ref="uToast" />
    <u-action-sheet
      :list="stationList"
      v-model="showSelect"
      @click="commit"
    ></u-action-sheet>
    <u-action-sheet
      :list="typeList"
      v-model="show2"
      @click="chooseType"
    ></u-action-sheet>
    <view class="fffbg">
      <view class="date">
        <view @click="showCan" class="row">
          日期：{{ date }} >
        </view>
        <u-calendar
          :max-date="maxDate"
          @change="chooseDate"
          v-model="show"
          :mode="mode"
        ></u-calendar>
      </view>
			<view class="form">
				<u-form :model="form" ref="uForm" :label-width="150">
					<u-form-item label="高压"
						><u-input v-model="form.pressureHigh" placeholder="请输入高压"
					/></u-form-item>
					<u-form-item label="低压"
						><u-input v-model="form.pressureLow" placeholder="请输入低压"
					/></u-form-item>
					<u-form-item label="该月经期">
						<view @click="showCan2">
              <text v-if="form.period">{{ form.period }}</text>
              <text class="choose" v-if="!form.period">请选择</text>
            </view>
					</u-form-item>
					<u-form-item label="日饮水量">
						<u-input v-model="form.urine" placeholder="日饮水量(ml)"/>
					</u-form-item>
					<u-form-item label="体温(℃)">
						<u-input v-model="form.temperature" placeholder="请输入体温"/>
					</u-form-item>
					<u-form-item label="体重(kg)">
						<u-input v-model="form.weight" placeholder="请输入体重" @input="blurData()" />
					</u-form-item>
					<u-form-item label="身高(m)">
						<u-input v-model="form.height" placeholder="请输入身高" @input="blurData()"/>
					</u-form-item>
					<u-form-item label="bmi">
						<view>{{ form.bmi }}</view>
					</u-form-item>
				</u-form>
			</view>
    </view>
    <button class="submit" @click="submit">上传</button>
    <view class="advice" v-if="advices.length">
      建议：
      <view v-for="(item, index) in advices" :key="index" style="margin-bottom: 8rpx;">
        {{index+1}}：{{item}}
      </view>
    </view>
    <view class="advice" v-if="!advices.length && form.id">
      各项指标正常！
    </view>
    <view class="advice" v-if="!advices.length && !form.id">
      当日还未填写，请上传~
    </view>
  </view>
</template>

<script>
import moment from "moment";
import { getHealth, updateHealth, addHealth, getPeriod, updatePeriod, addPeriod } from "../../api/system/api";
export default {
  data() {
    return {
      show: false,
      show2: false,
      date: "",
      showSelect: false,
      stationList: [],
			mode: 'range',
      advices: [],
      form: {
				pressureLow: '',
				pressureHigh: '',
				weight: '',
				height: '',
				period: '',
				urine: '',
        temperature: '',
				bmi: ''
			},
      periodInfo: {},
      minDate: moment().subtract(14, "days").format("YYYY-MM-DD"),
      maxDate: moment().add(14, "days").format("YYYY-MM-DD"),
      userInfo: {},
      period: '',
      typeList: [{
        text: '点错了'
      }, {
        text: '增加'
      }, {
        text: '修改'
      }]
    };
  },
  methods: {
    chooseType(index) {
      console.log(index)
      if (index === 0) {

      } else if (index === 1) {
        addPeriod({
          period: this.dataE.startDate + '~' + this.dataE.endDate,
          date: this.dataE.startDate.slice(0, 7),
          userId: this.userInfo.id
        }).then(res => {
          if (res.code === 200) {
            this.form.period = this.dataE.startDate + '~' + this.dataE.endDate;
            this.refreshAdvice()
            this.period = this.dataE.startDate + '~' + this.dataE.endDate;
          } else {
            this.$refs.uToast.show({
              title: "经期选择失败",
              type: "error",
            });
          }
        })
      } else if (index === 2) {
        updatePeriod(this.periodInfo.id, {
          period: this.dataE.startDate + '~' + this.dataE.endDate,
          date: this.dataE.startDate.slice(0, 7),
          userId: this.userInfo.id
        }).then(res => {
          if (res.code === 200) {
            this.refreshAdvice()
            this.form.period = this.dataE.startDate + '~' + this.dataE.endDate;
            this.period = this.dataE.startDate + '~' + this.dataE.endDate;
          } else {
            this.$refs.uToast.show({
              title: "经期选择失败",
              type: "error",
            });
          }
        })
      }
    },
    showCan() {
      this.mode = 'date';
			this.minDate = moment().subtract(14, "days").format("YYYY-MM-DD")
			this.maxDate = moment().add(14, "days").format("YYYY-MM-DD")
			this.isForm = false;
      this.show = true;
    },
    chooseDate(e) {
      console.log(e, this.isForm, this.periodInfo)
			if (this.isForm) {
        // 经期的添加或者修改
        if (!this.periodInfo.id) {
          // 增加经期
          addPeriod({
            period: e.startDate + '~' + e.endDate,
            date: e.startDate.slice(0, 7),
            userId: this.userInfo.id
          }).then(res => {
            if (res.code === 200) {
              this.form.period = e.startDate + '~' + e.endDate;
              this.refreshAdvice()
              this.period = e.startDate + '~' + e.endDate;
            } else {
              this.$refs.uToast.show({
                title: "经期选择失败",
                type: "error",
              });
            }
          })
        } else {
          console.log(this.periodInfo.date, e.startDate.slice(0, 7))
          if (this.periodInfo.date === e.startDate.slice(0, 7)) {
            console.log('这个月登记过了')
            this.show2 = true;
            this.dataE = e
            return
          }
          
        }
			} else {
				this.date = e.result;
        this.getData()
			}
    },
    refreshAdvice() {
      this.advices = []
      if (this.form.pressureLow && Number(this.form.pressureLow) < 60) {
        this.advices.push('正常血压低压范围60~80,您的低压偏低，建议：适当增加食盐用量、增加营养、加强体育锻炼')
      }
      if (this.form.pressureLow && Number(this.form.pressureLow) > 80) {
        this.advices.push('正常血压低压范围60~80,您的低压偏高，建议：适当增加食盐用量、增加营养、加强体育锻炼')
      }
      if (this.form.pressureHigh && Number(this.form.pressureHigh) > 140) {
        this.advices.push('正常血压高压范围90~140,您的高压偏高，建议：合理饮食、保持良好生活习惯、严重情况下药物治疗')
      }
      if (this.form.pressureHigh && Number(this.form.pressureHigh) < 90) {
        this.advices.push('正常血压高压范围90~140,您的高压偏低，建议：合理饮食、保持良好生活习惯、严重情况下药物治疗')
      }
      if (this.form.bmi && Number(this.form.bmi) > 24) {
        this.advices.push('BMI即为体质量指数，正常范围为18.5-24 kg/m2，建议：饮食调理、适当运动')
      }
      if (this.form.bmi && Number(this.form.bmi) < 18.5) {
        this.advices.push('BMI即为体质量指数，正常范围为18.5-24 kg/m2，建议：日常生活中适量多摄入营养物质,均衡饮食,可多进食牛肉、鱼肉、鸡蛋、牛奶、新鲜瓜果、蔬菜等高蛋白、高营养食物。')
      }
      if (this.form.urine && Number(this.form.urine) < 1500) {
        this.advices.push('平均每天的饮水量一般在1500~2000毫升，建议：饮食调理、多喝水。')
      }
      if (this.form.temperature && Number(this.form.temperature) > 37.3) {
        this.advices.push('您已发烧，建议：饮食调理、吃药、多喝水。')
      }

      // 处理经期相关的建议
      if (this.form.period) {
        let periods = this.form.period.split(';')
        for (let period of periods) {
          let diff = moment(period[1]).diff(moment(period[0]), 'days')
          if (diff < 21) {
            if (!this.advices.includes('例假周期也就是月经周期，正常范围期一般为21-35天，建议：前往医院检查。')) {
              this.advices.push('例假周期也就是月经周期，正常范围期一般为21-35天，建议：前往医院检查。')
            }
          } else if (diff > 35) {
            if (!this.advices.includes('例假周期也就是月经周期，正常范围期一般为21-35天，建议：前往医院检查。')) {
              this.advices.push('例假周期也就是月经周期，正常范围期一般为21-35天，建议：前往医院检查。')
            }
          }
        }
      }
    },
		showCan2() {
      this.mode = 'range';
			this.minDate = moment(this.date).startOf('month').format("YYYY-MM-DD");
			this.maxDate = moment(this.date).endOf('month').format("YYYY-MM-DD");
			this.isForm = true;
      this.show = true;
		},
    chooseStation(type) {
      this.type = type;
      this.showSelect = true;
    },
    commit(index) {
      this[this.type] = this.stationList[index].text;
    },
    getData() {
      getHealth({
        date: this.date,
        userId: this.userInfo.id
      }).then(res => {
        console.log(res)
        if (res.code === 200 && res.data.data.length) {
          this.form = res.data.data[0]
        } else {
          this.form = {
            pressureLow: '',
            pressureHigh: '',
            weight: '',
            height: '',
            urine: '',
            temperature: '',
            bmi: ''
          }
        }
        getPeriod({
          date: this.date.slice(0, 7),
          userId: this.userInfo.id
        }).then(rs => {
          if (rs.data.data.length) {
            console.log(this.date.split('-')[2])
            let day = Number(this.date.split('-')[2])
            if (rs.data.data.length === 1) {
              this.periodInfo = rs.data.data[0]
            } else if (rs.data.data.length === 2) {
              if (day <= 15) {
                this.periodInfo = rs.data.data[0]
              } else {
                this.periodInfo = rs.data.data[1]
              }
            } else {
              if (day <= 10) {
                this.periodInfo = rs.data.data[0]
              } else if (day <= 20) {
                this.periodInfo = rs.data.data[1]
              } else {
                this.periodInfo = rs.data.data[2]
              }
            }
            this.form.period = rs.data.data.map(v => v.period).join(';')
            this.period = rs.data.data.map(v => v.period).join(';')
          }
          this.refreshAdvice()
        })
      })
    },
    submit() {
			if (!this.userInfo.id) {
				this.$refs.uToast.show({
				  title: "请先登录",
				  type: "error",
				});
				return
			}
      if (this.form.id) {
        updateHealth(this.form.id, {
          ...this.form,
          date: this.date
        }).then(res => {
          this.$refs.uToast.show({
            title: "编辑成功",
            type: "success",
          });
          this.refreshAdvice()
        })
      } else {
        addHealth({
          ...this.form,
          date: this.date,
          userId: this.userInfo.id
        }).then(res => {
          console.log(this.period)
          if (res.code === 200) {
            this.$refs.uToast.show({
              title: "上传成功",
              type: "success",
            });
            this.form = {
              ...res.data,
              period: this.period
            }
            this.refreshAdvice()
          }
        })
      }
    },
    blurData() {
      if (this.form.height && this.form.weight) {
        this.form.bmi = (Number(this.form.weight) / (Number(this.form.height) * Number(this.form.height))).toFixed(1)
      }
    }
  },
  created() {
    uni.getStorage({     
      key:'userInfo',
      success: (res) => {
        this.userInfo = res.data;
        console.log(this.userInfo)
        this.date = moment().format("YYYY-MM-DD");
        this.getData()
      },
			error: (res) => {
				console.log(res)
			}
    })
  },
  onTabItemTap() {
    uni.getStorage({     
      key:'userInfo',
      success: (res) => {
        this.userInfo = res.data;
        console.log(this.userInfo)
        this.date = moment().format("YYYY-MM-DD");
        this.getData()
      }
    })
  }
};
</script>

<style lang="scss" scoped>
.container {
  background-color: #f7f7f7;
  min-height: 100vh;
  overflow: hidden;
}
.header {
  width: 100%;
  height: 500rpx;
  .img {
    width: 100%;
    height: 100%;
  }
}
.date {
  display: flex;
  padding: 30rpx 30rpx 0 30rpx;
  font-size: 30rpx;
  font-weight: bold;
  justify-content: space-between;

  .img {
    width: 60rpx;
    height: 60rpx;
  }
}

.submit {
  margin: 30rpx auto;
  border: none;
  width: calc(100% - 60rpx);
  height: 86rpx;
  line-height: 86rpx;
  box-sizing: border-box;
  border-radius: 15rpx;
  background-color: #e58b8a;
  color: #ffffff;
}
.row {
  width: 100%;
	text-align: center;
}
.form {
  padding: 30rpx;
}
.choose {
  font-size: 28rpx;
  color: #c2c8d4;
}
.advice {
  padding: 20rpx;
  width: calc(100% - 60rpx);
  margin: 30rpx;
  border: 1rpx dashed orangered;
}
.fffbg {
  width: calc(100% - 60rpx);
  margin: 30rpx;
  background: #fff;
  border-radius: 16rpx;
}
</style>
